package com.pxmeta.feishu.service;

import com.alibaba.fastjson.JSONObject;
import com.pxmeta.common.core.redis.RedisCache;
import com.pxmeta.common.utils.HttpUtils;
import com.pxmeta.common.utils.JsonUtils;
import com.pxmeta.common.utils.RedisUtils;
import com.pxmeta.common.utils.StringUtils;
import com.pxmeta.feishu.dto.SendMegDTO;
import com.pxmeta.feishu.vo.AccessTokenVO;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class FeishuService {

    private final RedisCache redisCache;
    public static final String KEY_TENANT_ACCESS_TOKEN = "feishu_tenant_access_token_%s";

    public static final String TENANT_ACCESS_TOKEN_URL = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
    public static final String SEND_MSG_URL = "https://open.feishu.cn/open-apis/im/v1/messages";

    public String getTenantAccessToken(String appId, String appSecret){
        String key = String.format(KEY_TENANT_ACCESS_TOKEN,appId);
        String accessToken = redisCache.getCacheObject(key);
        if (StringUtils.isBlank(accessToken)){
            AccessTokenDTO dto = new AccessTokenDTO();
            dto.setAppId(appId);
            dto.setAppSecret(appSecret);
            JSONObject body = JsonUtils.toJsonObject(dto);
            JSONObject result = HttpUtils.doPost(TENANT_ACCESS_TOKEN_URL, body);
            Integer expire = result.getInteger("expire");
            accessToken = result.getString("tenant_access_token");
            redisCache.setCacheObject(key, accessToken,expire-10, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    public void sendMsg(String receiveId, String content, String msgType, String accessToken){
        SendMegDTO dto = new SendMegDTO();
        dto.setMsgType(msgType);
        dto.setContent(content);
        dto.setReceiveId(receiveId);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization","Bearer "+accessToken);
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        JSONObject body = JsonUtils.toJsonObject(dto);
        HttpUtils.doPost(SEND_MSG_URL+"?receive_id_type=chat_id", body, httpHeaders);
    }



}
